package edu.hcmus.sow.dao;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.domain.FileRevision;

/**
 * DAO to manage FileRevision entities.
 * 
 */
@Repository
@Transactional
public class FileRevisionDAOImpl extends AbstractHibernateDAO<FileRevision, Integer> implements FileRevisionDAO {

   public List<FileRevision> getLatestVersionByFolderID(Integer folderID) throws DataAccessException {
      String queryString = "select fr from FileRevision fr join fetch fr.file f join fetch fr.userByCreatedBy u where fr.file.folderID = ? and "
            + "fr.revision >= all(select fr2.revision from FileRevision fr2 where fr.file = fr2.file)";
      // + "fr.revision >= all elements(fr.file.fileRevisions)";

      List<FileRevision> list = executeQuery(queryString, folderID);
      return list;
   }

   public List<FileRevision> getRevisionsListByFileID(Integer fileID) throws DataAccessException {
      String queryString = "from FileRevision fr join fetch fr.userByCreatedBy u where fr.file.id = ? order by revision DESC";
      List<FileRevision> list = executeQuery(queryString, fileID);

      return list;
   }

   public FileRevision getLatestVersionByFileID(Integer fileID) throws DataAccessException {
      String queryString = "from FileRevision fr join fetch fr.userByCreatedBy u where fr.file.id = ? order by revision DESC";
      List<FileRevision> list = executeQuery(queryString, 0, 1, fileID);

      return list.size() == 0 ? null : list.get(0);
   }
}
